package org.biojava.services.das.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.biojava.dasobert.das2.io.DasSourceWriter;
import org.biojava.dasobert.das2.io.DasSourceWriterImpl;
import org.biojava.dasobert.dasregistry.DasSource;
import org.biojava.services.das.dao.DasServer;
import org.biojava.utils.xml.PrettyXMLWriter;
import org.biojava.utils.xml.XMLWriter;

public class DasServerResponseWriter {
	
	public  void writeResponse(HttpServletResponse resp, List<DasServer> servers,  int total,int start, int end)
	throws ServletException, IOException {
		resp.setHeader("Content-Encoding","ISO-8859-1");
		resp.setHeader("Content-Type", ServletResponseWriter.XML_CONTENT_TYPE);
		resp.setHeader("X-DAS-Status", ServletResponseWriter.XDASOK);
		OutputStream s = resp.getOutputStream();

		PrintWriter pw = new PrintWriter(s);
		if(end==0)end=servers.size();
		XMLWriter xw = initServerResponse(pw, total, start, end);
		DasServerWriter writer = new DasServerWriterImpl();       
		for ( int i = 0 ; i< servers.size();i++){
			DasServer server = servers.get(i);
			writer.writeDasServer(xw, server);
		}
		xw.closeTag("SERVERS");
		xw.close();
		
	}
	
	
	private  XMLWriter initServerResponse(PrintWriter pw, int total, int start, int end) throws IOException{

		PrettyXMLWriter xw = new PrettyXMLWriter(pw);
		xw.printRaw("<?xml version='1.0' encoding='UTF-8' ?>");   
		//xw.printRaw("<?xml-stylesheet type=\"text/xsl\" href=\"das.xsl\"?>");    
		//System.out.println("XXXXX");
		xw.openTag("SERVERS");
		if(start!=0 ){
		xw.attribute("total",String.valueOf(total));
		xw.attribute("start",  String.valueOf(start));
		xw.attribute("end",  String.valueOf(end));
		}
		//xw.attribute("xml:base","http://das.sanger.ac.uk/registry/das2/");
		return xw;

	}    

	
}
